<template>
  <div class="load-more-list">
    <slot :list="list" :total-data="totalData" />
    <slot name="empty">
      <view v-if="!list.length" class="mt-10">
        <u-empty :text="emptyText" mode="list" />
      </view>
    </slot>
    <up-loadmore v-if="loadMore" class="mt-4" :status="status" @loadmore="onReachBottom" />
  </div>
</template>

<script setup lang="ts">
import type { IResponseRows } from '@/utils/request/type';

const props = defineProps({
  emptyText: {
    type: String,
    default: '暂无数据',
  },
  requestFn: {
    type: Function,
    default: () => {},
  },
  pageSize: {
    type: Number,
    default: 10,
  },
  requestParams: {
    type: Object,
    default: () => {},
  },
  loadMore: {
    type: Boolean,
    default: true,
  },
});

const { requestFn, pageSize, requestParams, loadMore } = props;
const list = ref<unknown[]>([]);
const totalData = ref(0);
const currentPage = ref(1);

const status = ref('loadmore');

// 获取数据
const getData = () => {
  status.value = 'loading';

  requestFn({ pageSize, pageNum: currentPage.value, ...requestParams }).then(
    (res: IResponseRows<unknown[]>) => {
      list.value = [...list.value, ...res.rows];
      totalData.value = res.total;
      status.value = totalData.value > list.value.length ? 'loadmore' : 'nomore';
    },
  );
};
const refresh = () => {
  list.value = [];
  currentPage.value = 1;
  status.value = 'loadmore';
  getData();
};
// 触底
const onReachBottom = () => {
  if (status.value === 'nomore' || !loadMore)
    return;
  currentPage.value++;
  getData();
};
onMounted(() => {
  getData();
});
defineExpose({
  refresh,
  list,
  onReachBottom,
});
</script>

<style lang="scss" scoped></style>
